package com.eipc.util;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.provider.MediaStore;
import android.util.Log;
import com.eipc.R;
import com.eipc.util.ContactList.Contact;
import com.eipc.util.ContactList.Contact.Phone;
import com.eipc.util.DBHelper.STATUS;
/**
 * 公共类
 * @author x_liaolijun
 *
 * 2010-9-4 上午11:40:05
 *  
 * Tools
 *
 */
public class Tools {
	
	public static String toDate(String str){
		if(str!=null && !"".equals(str) && str.length()>=8){
			return str.substring(0, 4)+"/"+str.substring(4, 6)+"/"+str.substring(6);
		}
		return str;
	}
	
	public static String toDate2(String str){
		if(str!=null && !"".equals(str) && str.length()>=8){
			return str.substring(4, 6)+"/"+str.substring(6);
		}
		return str;

	}
	
	public static String[] splitString(String str){
		if(str!=null){
			return str.split(";");
		}
		return null;
	}
	
	public static String removeClub(String str){
		if(str!=null){
			str = str.replace("( )", "");
			return str.replace("()", "");
		}
		return str;
	}
	
	public static String getCurrentTimeString(){
		Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
		String created = buildZero((calendar.get(Calendar.MONTH)+1)) + "/"
		+ buildZero(calendar.get(Calendar.DAY_OF_MONTH)) + " "
		+ buildZero(calendar.get(Calendar.HOUR_OF_DAY)) + ":"
		+ buildZero(calendar.get(Calendar.MINUTE));
		return created;
	}
	
	public static String getAlertDateString(int i){
		Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
		String created = buildZero((calendar.get(Calendar.MONTH)+1)) + "/"
		+ buildZero(calendar.get(Calendar.DAY_OF_MONTH)) + " "
		+ buildZero(calendar.get(Calendar.HOUR_OF_DAY)+i);
		return created;
	}
	
	public static String getCurrentDateString(){
		Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+8"));
		String created = buildZero((calendar.get(Calendar.MONTH)+1)) + "/"
		+ buildZero(calendar.get(Calendar.DAY_OF_MONTH));
		return created;
	}
	
	private static String buildZero(int number){
		if(number>9)
			return String.valueOf(number);
		else
			return "0"+number;
	}

	public static void sendMsg(Context Context, String phoneNumber, String text) {
		Uri uri = Uri.parse("smsto:" + phoneNumber);
		Intent it = new Intent(Intent.ACTION_SENDTO, uri);
		it.putExtra("sms_body", text);
		Context.startActivity(it);
	}

	public static void sendCall(Context Context, String phoneNumber) {
		Uri uri = Uri.parse("tel:"+phoneNumber);    
		Intent it = new Intent(Intent.ACTION_DIAL, uri);    
		Context.startActivity(it);   
	}
	
	public static boolean isNear(String t){
        Date d = parClientData(t);
        if(d!=null){
        	return d.after(new Date());
        }
		return false;
	}
	
	public static Date parClientData(String d){
    	SimpleDateFormat sdf = new SimpleDateFormat("MM/dd HH:mm");
    	try {
			return getRealDateB(sdf.parse(d),1);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
    }
	
	public static Date getRealDateB(Date date,int i){
		  Calendar cal = Calendar.getInstance();
		  Calendar c = Calendar.getInstance();
		  c.setTime(date);
		  c.set(Calendar.YEAR,cal.get(Calendar.YEAR));
		  c.set(Calendar.HOUR_OF_DAY,c.get(Calendar.HOUR_OF_DAY)+i);
		  return c.getTime();
	}
//	/**
//	 * 建群组
//	 */
//	public static void buildGroup(Context context){
//		ContentResolver resolver = context.getContentResolver();  
//        resolver.delete(ContactsContract.Groups.CONTENT_URI, ContactsContract.Groups.TITLE+" = ? ", new String[]{"EIPC"});
//		ContentValues values = new ContentValues();
//		values.put(ContactsContract.Groups.TITLE, "EIPC");
//		values.put(ContactsContract.Groups.NOTES, "EIPC");
//		resolver.insert(ContactsContract.Groups.CONTENT_URI, values);
//	}
	
	
	/**
	  * 
	  * @param url 获取网络图片
	  * @return  imView.setImageBitmap(returnBitMap(imageUrl));
	  */
	public static Bitmap returnBitMap(String url) {
		Log.e("------------getURLBitmap","-----begin-----");
		  Bitmap bitmap = null;	
		  URL imageUrl = null;
		  try{
		    imageUrl = new URL(url);
		  }catch (MalformedURLException e){
		    Log.e("------------getURLBitmap","error : ",e);
		  }
		  try{
		    HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
		    conn.setDoInput(true);
	        conn.setConnectTimeout(40000);
	        conn.setReadTimeout(30000);
	        Log.e("------------getURLBitmap","-----begin connect-----");
		    conn.connect();
		    InputStream is = conn.getInputStream();
	        int length = (int) conn.getContentLength();
	        Log.e("------------getURLBitmap ContentLength :",""+length);
	        if (length != -1) {
	            byte[] imgData = new byte[length];
	            byte[] temp = new byte[512];
	            int readLen = 0;
	            int destPos = 0;
	            while ((readLen = is.read(temp)) > 0) {
	            	System.arraycopy(temp,0,imgData,destPos,readLen);
	            	destPos += readLen;
	            	//Log.e("------------getURLBitmap status :",destPos+"/"+length);
	            }
	            bitmap = BitmapFactory.decodeByteArray(imgData,0,imgData.length);
	        }
		    is.close();
		    conn.disconnect();
		  }catch (Exception e){
			  Log.e("------------getURLBitmap","error : ",e);
		  }
		  return bitmap;
	}
	
	/**
	 * insert contacts
	 * @param context
	 * @param cursor
	 */
	public static void buildContacts(Context context,Cursor cursor){
		Log.e("------begin buildContacts-------",String.valueOf(cursor!=null?cursor.getCount():"0"));
		Map<String,Boolean> hp = new HashMap<String,Boolean>();
		ContentResolver resolver = context.getContentResolver();
		Cursor c = null;
		try {
			if(cursor!=null && cursor.getCount()>0){
				c = resolver.query(Data.CONTENT_URI,new String[]{android.provider.ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID}, android.provider.ContactsContract.CommonDataKinds.Phone.LABEL+" = ? ", new String[]{"EIPC"},null);
				if(c!=null && c.getCount()>0){
					c.moveToFirst();
					ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); 
					String[] args =null;
					do{
						args = new String[] {c.getString(0)}; 
						ops.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI).withSelection(RawContacts._ID + "=?", args) .build());
						resolver.applyBatch(ContactsContract.AUTHORITY, ops);
					}
					while(c.moveToNext());
				}
				resolver.delete(Data.CONTENT_URI, android.provider.ContactsContract.CommonDataKinds.Phone.LABEL+" = ? ", new String[]{"EIPC"});
//				ContactList list = new ContactList();
//				ArrayList<Phone> phones = null;
//				Phone phone = null;
//				cursor.moveToFirst();
//				do{
//					phones = new ArrayList<ContactList.Contact.Phone>();
//					phone = new Phone(cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.FIELD_PERSON_MOBILE)), android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
//					phones.add(phone);
//					hp.put(cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.FIELD_PERSON_MOBILE)),true);
//					list.addContact(new Contact(cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.FIELD_PERSON_NAME)),phones , null, null, null, null));
//				}while(cursor.moveToNext());
//				list.insert(resolver);
				
			}
			c = resolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
			Log.e("------begin c -------",String.valueOf(c!=null?c.getCount():"0"));
			if(c!=null&&c.getCount()>0){
				c.moveToFirst();
				do{
					try{
						long contactId = c.getLong(c.getColumnIndex(ContactsContract.Contacts._ID)); //获取联系人的ID号，在SQLite中的数据库ID
						final String lookupKey = c.getString(c.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
						Uri mSelectedContactUri = Contacts.getLookupUri(contactId, lookupKey);
						Cursor phone = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "+ contactId, null, null);
						while(phone.moveToNext()){
							String p = phone.getString(phone.getColumnIndex (ContactsContract.CommonDataKinds.Phone.NUMBER)); //手机号码字段联系人可能不止一个
							if(hp.containsKey(p)){
								Log.e("-----xxxxxxx-----phone-----xxxxxxx------",p);
								resolver.delete(mSelectedContactUri, null, null);
								phone.close();
								break;
							}
						}
						
					}catch(Exception ex){
						Log.e("-----------","------------",ex);	
					}
				}while(c.moveToNext());
			}
		}catch (Exception e) {
		    Log.e("xxxxxxxxxx","xxxxxxxxx",e);	
		}
		finally{
			if(cursor!=null) cursor.close();
			if(c!=null) cursor.close();
		}
	}
	
	/**
	 * 照相
	 * @param activity
	 * @param requestCode
	 */
	public final static void takePicture(Activity activity,int requestCode){
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		activity.startActivityForResult(intent, requestCode);
	}
	
	public final static int getIconByType(String type){
		if("指挥中心".equals(type)){
			return R.drawable.type_control_center;
		}
		else if("总经理室".equals(type)){
			return R.drawable.type_manager_office;
		}
		else if("天气信息".equals(type)){
			return R.drawable.type_weahter_info;
		}
		else if("赛事信息".equals(type)){
			return R.drawable.type_game_info;
		}
		else if("安保信息".equals(type)){
			return R.drawable.type_safe_info;
		}
		else if("交通信息".equals(type)){
			return R.drawable.type_traffic_info;
		}
		else if("会议通知".equals(type)){
			return R.drawable.type_meeting_notice;
		}
		else if("赛场保障".equals(type)){
			return R.drawable.type_security_info;
		}
		else if("咨询服务".equals(type)){
			return R.drawable.type_consult_center;
		}
		else if("贵宾接待".equals(type)){
			return R.drawable.type_vip_service;
		}
		else if("员工通知".equals(type)){
			return R.drawable.type_employee_info;
		}
		else if("其他".equals(type)){
			return R.drawable.type_other;
		}
		return R.drawable.type_other;
	}
	
	public final static int getIconByType(String type, String isRead){
		
//		Log.e("Classify", String.valueOf(isRead.equals(String.valueOf(STATUS.IMPORT_NOTICE_READED))));
		
		if ( !isRead.equals(String.valueOf(STATUS.IMPORT_NOTICE_READED)))
		{
			return R.drawable.type_new;
//			if("指挥中心".equals(type)){
//				return R.drawable.type_control_center2;
//			}
//			else if("总经理室".equals(type)){
//				return R.drawable.type_manager_office2;
//			}
//			else if("天气信息".equals(type)){
//				return R.drawable.type_weahter_info2;
//			}
//			else if("赛事信息".equals(type)){
//				return R.drawable.type_game_info2;
//			}
//			else if("安保信息".equals(type)){
//				return R.drawable.type_safe_info2;
//			}
//			else if("交通信息".equals(type)){
//				return R.drawable.type_traffic_info2;
//			}
//			else if("会议通知".equals(type)){
//				return R.drawable.type_meeting_notice2;
//			}
//			else if("赛场保障".equals(type)){
//				return R.drawable.type_security_info2;
//			}
//			else if("咨询服务".equals(type)){
//				return R.drawable.type_consult_center2;
//			}
//			else if("贵宾接待".equals(type)){
//				return R.drawable.type_vip_service2;
//			}
//			else if("员工通知".equals(type)){
//				return R.drawable.type_employee_info2;
//			}
//			else if("其他".equals(type)){
//				return R.drawable.type_other2;
//			}
		}
		else
		{
			if("指挥中心".equals(type)){
				return R.drawable.type_control_center;
			}
			else if("总经理室".equals(type)){
				return R.drawable.type_manager_office;
			}
			else if("天气信息".equals(type)){
				return R.drawable.type_weahter_info;
			}
			else if("赛事信息".equals(type)){
				return R.drawable.type_game_info;
			}
			else if("安保信息".equals(type)){
				return R.drawable.type_safe_info;
			}
			else if("交通信息".equals(type)){
				return R.drawable.type_traffic_info;
			}
			else if("会议通知".equals(type)){
				return R.drawable.type_meeting_notice;
			}
			else if("赛场保障".equals(type)){
				return R.drawable.type_security_info;
			}
			else if("咨询服务".equals(type)){
				return R.drawable.type_consult_center;
			}
			else if("贵宾接待".equals(type)){
				return R.drawable.type_vip_service;
			}
			else if("员工通知".equals(type)){
				return R.drawable.type_employee_info;
			}
			else if("其他".equals(type)){
				return R.drawable.type_other;
			}
		}
		
		return R.drawable.type_other;
	}

}
